package com.excuse.excusebuilder.view.activity;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.widget.Button;
import android.widget.EditText;

import com.excuse.excusebuilder.R;
import com.excuse.excusebuilder.base.BaseActivity;
import com.excuse.excusebuilder.bean.User;
import com.excuse.excusebuilder.commen.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by U-nookia on 2017/4/21.
 */

public class SignUpActivity extends BaseActivity {
    @BindView(R.id.name_edt_sign_up)
    EditText nameEdtSignUp;
    @BindView(R.id.password_edt_sign_up)
    EditText passwordEdtSignUp;
    @BindView(R.id.btn_sign_up)
    Button btnSignUp;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @Override
    protected void initData() {
        initToolbar(toolbar,"注册");
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_sign_up;
    }

    @OnClick(R.id.btn_sign_up)
    public void onViewClicked() {
        String name = nameEdtSignUp.getText().toString();
        String password = passwordEdtSignUp.getText().toString();
        if (name.equals("")||password.equals("")){
            ToastUtil.makeShortToast(this,"输入不能为空");
            return;
        }
        User user = new User();
        user.setUsername(name);
        user.setPassword(password);
        user.setAvatarUrl("http://www.qqjay.com/uploads/allimg/160306/1_0PP4Q19.jpg");
        user.signUp(new SaveListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                if (e!=null){
                    ToastUtil.makeShortToast(SignUpActivity.this,e.toString());
                    return;
                }
                signInBmob(user);
            }
        });
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(SignUpActivity.this,SignInActivity.class));
        finish();
    }

    private void signInBmob(User user) {
        user.setUsername(nameEdtSignUp.getText().toString());
        user.setPassword(passwordEdtSignUp.getText().toString());
        user.login(new SaveListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                if (e!=null){
                    ToastUtil.makeShortToast(SignUpActivity.this,e.toString());
                    return;
                }
                startActivity(new Intent(SignUpActivity.this,MainActivity.class));
                finish();
                ToastUtil.makeShortToast(context,"注册成功");
            }
        });
    }
}
